import {deepFullCopy, messages} from "share/common";
/**
 * Created by Allen on 2018/4/2.
 */
import React from 'react'
import ReactDOM from 'react-dom'
import {connect} from 'react-redux'
import menuRoute from 'routes/menuRoute'
import {Table, Button, message, Icon, Select, Tooltip, Input, Popconfirm, Modal} from 'antd'
import enableSupplierService from 'containers/supplier-management/overview/enable-service/enable-service.service'
import 'styles/supplier-management/overview/cmbc-rule.scss'
import SyncData from 'containers/supplier-management/overview/supplier-detail/sync-data'
import errorMessage from 'share/errorMessage';

const Option = Select.Option;
const confirm = Modal.confirm;
const deadLineDateArray = [{label: '每月1日', value: '1'}, {label: '每月2日', value: '2'}, {label: '每月3日', value: '3'},
  {label: '每月4日', value: '4'}, {label: '每月5日', value: '5'}, {label: '每月6日', value: '6'}, {label: '每月7日', value: '7'},
  {label: '每月8日', value: '8'}, {label: '每月9日', value: '9'}, {label: '每月10日', value: '10'}, {
    label: '每月11日',
    value: '11'
  }, {label: '每月12日', value: '12'}, {label: '每月13日', value: '13'}, {label: '每月14日', value: '14'}, {
    label: '每月15日',
    value: '15'
  }, {label: '每月16日', value: '16'}, {label: '每月17日', value: '17'}, {label: '每月18日', value: '18'}, {
    label: '每月19日',
    value: '19'
  }, {label: '每月20日', value: '20'}, {label: '每月21日', value: '21'}, {label: '每月22日', value: '22'}, {
    label: '每月23日',
    value: '23'
  }, {label: '每月24日', value: '24'}, {label: '每月25日', value: '25'}, {label: '每月26日', value: '26'}, {
    label: '每月27日',
    value: '27'
  }, {label: '每月28日', value: '28'}, {label: '每月29日', value: '29'}, {label: '每月30日', value: '30'}, {
    label: '每月31日',
    value: '31'
  },]; //报销期限的下拉框选项
const billMonthArray = [{label: '当月', value: 'CURRENT_MONTH'}, {label: '上月', value: 'LAST_MONTH'},
  {label: '当月,上月', value: 'CURRENT_MONTH,LAST_MONTH'}];

//账单月下拉框选项

class CmbcRule extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      cmbcData: [],
      showModal: false,//同步消费数据Modal
      showModalOkDisabled: true,
      loading: false,
      cmbcColumns: [{
        title: messages('supplier.key1'/*账户信息(必填)*/),
        children: [{
          title: messages('supplier.key2'/*客户号*/),
          dataIndex: 'clientId',
          key: 'clientId',
          width: 100,
          render: (text, record,index) => (
            <span>
              <Input type="number" placeholder={messages('common.please.enter')} defaultValue={record.clientId}
                     onChange={e => this.handleChange(e.target.value, index, 'clientId')}/>
            </span>
          )
        }, {
          title: messages('supplier.key3'/*密码*/),
          dataIndex: 'clientSecret',
          key: 'clientSecret',
          width: 100,
          render: (text, record, index) => (
            <span>
              <Input type="password" placeholder={messages('common.please.enter')} maxLength="8"
                     defaultValue={record.clientSecret}
                     onChange={e => this.handleChange(e.target.value, index, 'clientSecret')}/>
            </span>
          )
        }, {
          title: messages('supplier.key4'/*成本中心号*/),
          dataIndex: 'corNum',
          key: 'corNum',
          width: 100,
          render: (text, record, index) => (
            <span>
              <Input type="number" placeholder={messages('common.please.enter')} defaultValue={record.corNum}
                     onChange={e => this.handleChange(e.target.value, index, 'corNum')}/>
            </span>
          )
        }]
      }, {
        title: <Tooltip title="设置后系统将在报销期限日凌晨检查未审核通过的费用或商务卡消费，并标记为已逾期">
          <span>{messages('supplier.key5'/*逾期设置(非必填)*/)}</span>
        </Tooltip>,
        children: [{
          title: messages('supplier.key6'/*报销期限*/),
          dataIndex: 'deadLineDate',
          key: 'deadLineDate',
          width: 100,
          render: (text, record, index) => (
            <span>
               <Select
                 showSearch
                 style={{width: '100%'}}
                 defaultValue={record.deadLineDate ? record.deadLineDate : []}
                 placeholder={messages('common.please.select')}
                 optionFilterProp="children"
                 onChange={e => this.handleChange(e, index, 'deadLineDate')}
               >
                 {deadLineDateArray.map((item, index) => (
                   <Option key={item.value} value={item.value}>{item.label}</Option>
                 ))}
            </Select>
            </span>
          )
        }, {
          title: messages('supplier.key7'/*账单月*/),
          dataIndex: 'billMonth',
          key: 'billMonth',
          width: 150,
          render: (text, record, index) => (
            <span>
              <Select
                style={{width: '100%'}}
                defaultValue={record.billMonth ? record.billMonth : []}
                placeholder={messages('common.please.select')}
                onChange={e => this.handleChange(e, index, 'billMonth')}
              >
                {billMonthArray.map((item, index) => (
                  <Option key={item.value} value={item.value}>{item.label}</Option>
                ))}
              </Select>
            </span>
          )
        }]
      }, {
        title: messages('common.operation')/*操作(*/,
        dataIndex: 'operate',
        key: 'operate',
        width: 50,
        render: (text, record,index) => (
          <span>
              <Popconfirm onConfirm={(e) => this.handleDelete(e, record,index)}
                          title={messages('supplier.key8'/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
                <a href="#" onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}>{messages('common.delete')}</a>
              </Popconfirm>
            </span>
        )
      }],
      supplierDashboard: menuRoute.getRouteItem('overview', 'key'),
    };
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.params && (nextProps.params.reLoading && !this.props.params.reLoading)) {
      this.setState({
        cmbcData: nextProps.params.nowCmbcData ? deepFullCopy(nextProps.params.nowCmbcData.cmbcData) : [],
      });
    }
  }

  //新增账户信息添加表格行
  addRow = () => {
    const {cmbcData} = this.state;
      const newData = {
        clientId: '',
        clientSecret: '',
        corNum: '',
        deadLineDate: '',
        billMonth: ''
      };
      this.setState({cmbcData: [...cmbcData, newData]});
  };

  //商务卡删除行
  handleDelete = (e, record,index) => {
    const {cmbcData} = this.state;
    cmbcData.delete(cmbcData[index])
    this.setState({cmbcData});
  };

  handleChange = (value, index, colunm) => {
    let {cmbcData}=this.state;
    if(cmbcData[index]){
      cmbcData[index][colunm]=value;
      this.setState({cmbcData})
    }
  };

  //保存
  handleSave = () => {

    const {cmbcData} = this.state;
    cmbcData.map(item => {
      if (item.billMonth instanceof Array) {
        item.billMonth = item.billMonth.join(',');
      }
    });
    let params = {
      status: 1,
      tenantBankCardCfgList: cmbcData
    };
    if (cmbcData.length === 0) {
      let that = this;
      const closeModal = confirm({
        title: messages('supplier.key98'/*无有效账户信息，将自动关闭该服务*/),
        content: messages('supplier.key99'/*关闭后不能在汇联易中使用招行商务卡服务*/),
        okText: messages('supplier.key100'/*继续关闭*/),
        onOk() {
          return new Promise((resolve, reject) => {
            enableSupplierService.openCMBC(params).then(resp => {
              if (resp.status === 200) {
                closeModal.destroy();
                that.context.router.push(`${that.state.supplierDashboard.url}`);
                resolve();
              }
            })
          }).catch(() => {
            reject();
          });
        },
        onCancel() {
        },
      });
      return;
    }
    let verifyId = cmbcData.some(item => {      //验证客户号位数
      return item.clientId.length !== 8
    });
    if (verifyId) {
      message.error('客户号为8位');
      return;
    }
    let verifySecret = cmbcData.some(item => {  //验证密码位数
      return item.clientSecret.length !== 8
    });
    if (verifySecret) {
      message.error('密码为8位');
      return;
    }
    let verifyCorNum = cmbcData.some(item => {  //验证成本中心号位数
      return item.corNum.length !== 10
    });
    if (verifyCorNum) {
      message.error('成本中心号为10位');
      return;
    }
    this.setState({loading: true});
    enableSupplierService.openCMBC(params).then(resp => {
      if (resp.data.success === true) {
        this.syncDataRef && this.syncDataRef.setState({data: resp.data.rows ? resp.data.rows.tenantBankCardCfgList : []});
        this.props.cmbcRuleDataonChange(resp.data.rows ? resp.data.rows.tenantBankCardCfgList : []);
        message.success(messages('supplier.key101'/*保存成功*/));
        this.setState({loading: false, cmbcData: []});
        this.props.close()
      } else {
        this.setState({loading: false, cmbcData: []});
        message.error(resp.data.message);
        this.props.close()
      }
    }).catch(error => {
      errorMessage(error.response,messages('common.save.filed'));
      this.setState({loading: false})
    })
  };

  onCancel = () => {
    this.props.close();
    this.setState({cmbcData: []});
  };
  handleSyncData = () => {
    if (this.syncDataRef && this.syncDataRef.state && this.syncDataRef.state.dataStatusChange) {
      this.syncDataRef.getList();
      this.syncDataRef.setState({data: [], dataStatusChange: false, selectedRowKeys: [], selectedRows: []})
      this.setState({showModalOkDisabled: true})
    }
    this.setState({showModal: true})
  }

  handleModalOK = () => {
    this.syncDataRef.confirmSyncData();
  }
  handleModalCancel = () => {
    this.setState({showModal: false})
  }

  render() {

    const {cmbcData, cmbcColumns, loading, showModal, showModalOkDisabled} = this.state;
    return (
      <div className="cmbc-rule">
        <div style={{marginBottom: 15}}><Icon type="setting"/><a onClick={this.handleSyncData}>{messages('supplier.key102'/*同步消费数据*/)}</a></div>
        <Table
          columns={cmbcColumns}
          dataSource={cmbcData}
          rowKey="id"
          pagination={false}
          scroll={{x: 1100}}
          bordered
          size="middle"
        />
        <Button type="dashed" style={{width: '100%', marginTop: '10px'}} onClick={() => this.addRow()}>
          <Icon type="plus"/> {messages('supplier.key63'/*新增账户信息*/)}
        </Button>

        <div className="slide-footer">
          <Button type="primary" htmlType="submit" onClick={this.handleSave} loading={loading}>
            {messages('common.save')}</Button>
          <Button onClick={this.onCancel}>{messages('common.back')}</Button>
        </div>
        {/*同步消费时间MODal*/}
        <Modal
          title={messages('supplier.key102'/*同步消费数据*/)}
          visible={showModal}
          width={800}
          onCancel={this.handleModalCancel}
          footer={[
            <Button key="back" onClick={this.handleModalCancel}>{messages('common.back')/*返回*/}</Button>,
            <Button key="submit" disabled={showModalOkDisabled} type="primary" loading={loading}
                    onClick={this.handleModalOK}> {messages('supplier.key103'/*确认*/)}
            </Button>,
          ]}
          className="list-selector">
          <SyncData supplierName={this.props.params.supplierName}
                    wrappedComponentRef={(inst) => this.syncDataRef = inst}
                    handleModalCancel={this.handleModalCancel}
                    checkUserIsConfirm={(enabled) => {
                      this.setState({showModalOkDisabled: enabled})
                    }}
                    showModal={showModal} />
        </Modal>
      </div>
    )
  }
}

CmbcRule.contextTypes = {
  router: React.PropTypes.object
};

CmbcRule.propsType = {
  reLoading: React.PropTypes.bool,//是否重新加载
  cmbcRuleDataonChange: React.PropTypes.func,
}
CmbcRule.defaultProps = {
  cmbcRuleDataonChange: () => {
  }
}
function mapStateToProps(state) {
  return {}
}


export default connect(mapStateToProps, null, null, {withRef: true})(CmbcRule)
